package org.apache.ibatis.test.demo;

import org.testcontainers.shaded.com.google.common.collect.Lists;

import java.util.Iterator;
import java.util.List;

/**
 * @author clxmm
 * @Description
 * @create 2021-09-27 8:51 下午
 */

interface Interceptor {
  Object plugin(Object t, InterceptorChan chan);
}


class InterceptorA implements Interceptor {
  @Override
  public Object plugin(Object t, InterceptorChan chan) {
    System.out.println("InterceptorA");
//    return t;
    return chan.plugin(t);
  }
}

class InterceptorB implements Interceptor {
  @Override
  public Object plugin(Object t, InterceptorChan chan) {
    System.out.println("InterceptorB");
//    return t;
    return chan.plugin(t);
  }
}


class InterceptorC implements Interceptor {
  @Override
  public Object plugin(Object t, InterceptorChan chan) {
    System.out.println("InterceptorC");
    return t;
  }
}

class InterceptorChan {
  private List<Interceptor> interceptorList = Lists.newLinkedList();
  Iterator<Interceptor> iterator ;

  public void addInterceptor(Interceptor interceptor) {
    interceptorList.add(interceptor);
  }


  public Object pluginAll(Object o) {
    for (Interceptor interceptor : interceptorList) {
      o = interceptor.plugin(o, this);
    }

    return o;
  }


  public Object plugin(Object o) {

    if (iterator == null) {
      iterator = interceptorList.iterator();
    }

    if (iterator.hasNext()) {
      Interceptor next = iterator.next();
      next.plugin(o, this);
    }
    return o;
  }


}


public class InterceptorDemo {


  public static void main(String[] args) {
    InterceptorA interceptorA = new InterceptorA();
    InterceptorB interceptorB = new InterceptorB();
    InterceptorC interceptorC = new InterceptorC();

    InterceptorChan interceptorChan = new InterceptorChan();
    interceptorChan.addInterceptor(interceptorA);
    interceptorChan.addInterceptor(interceptorB);
    interceptorChan.addInterceptor(interceptorC);

    interceptorChan.plugin(new Object());

  }


}
